const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')

// 删除bundle中的注释
class MyPlugin {
    apply (compiler) {
        console.log('My Plugin start');
        compiler.hooks.emit.tap('MyPlugin', compilation => {
            for(const name in compilation.assets) {
                console.log(compilation.assets[name].source());
                if(name.endsWith('.js')) {
                    const contents = compilation.assets[name].source()
                    const withoutComments = contents.replace(/\/\*\*+\*\//g, '')
                    compilation.assets[name] = {
                        source: () => withoutComments,
                        size: () => withoutComments.length
                    }
                }
            }
        })
    }
}

module.exports = {
    mode: 'none',
    entry: './src/main.js',
    output: {
        filename: 'bundle.js',
        path: path.join(__dirname, 'dist'),
        // publicPath: 'dist/'
    },
    devServer: {
        contentBase: './public',
        proxy: {
            './api': {
                // http://localhost:8080/api/users -> https://api.github.com/api/users
                target: 'https://api.github.com',
                // https://api.github.com/api/users -> https://api.github.com/users
                pathREwrite: {
                    '^api': ''
                },
                // 不能使用localhost:8080 作为请求  Github 的主机名
                // 课后了解主机名是http协议中的相关概念

                changeOrigin: true
            }
        }
    },
    module: {
        rules: [
            {
                test: /.md$/,
                use: './markdown.loader.js'
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin(),
        // 用于生成 index.html
        new HtmlWebpackPlugin({
            title: 'Webpack Sample',
            meta: {
                viewport: 'with=device-width'
            },
            template: './src/index.html'
        }),
        new HtmlWebpackPlugin({
            filename: 'about.html'
        }),
        // 开发阶段不使用
        // new CopyWebpackPlugin([
        //     'public'
        // ]),
        new MyPlugin()
    ]
}